package com.ramos.kuaixiao.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.facebook.drawee.view.SimpleDraweeView;
import com.githang.statusbar.StatusBarCompat;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.entity.Customer;
import com.ramos.kuaixiao.utils.CommonLoading;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.ToastUtils;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class ErrorAddressActivity extends BaseAllTabActivity implements View.OnClickListener {
    private static final String TAG = "ErrorAddressActivity";
    TextView tv_aboutus;
    LinearLayout title_reback;
    TextView title_order;
    TextView tv_current_address;
    TextView tv_distance;
    Customer mCustomer;
    RelativeLayout rl_take_picture;
    private Uri photoUri;
    public String mImagePath;
    SimpleDraweeView sdv_picture;
    TextView tv_take_picture;
    CommonLoading loading;
    public final static int UPLOAD_SUCCESS1 = 200;
    public final static int UPLOAD_FAIL1 = 201;

    private RelativeLayout re_home_shop;
    private RelativeLayout re_home_order;
    private RelativeLayout re_home_task;
    private RelativeLayout re_home_my;
    private TextView tv_home_shop;
    private TextView tv_home_order;
    private TextView tv_home_task;
    private TextView tv_home_my;
    private ImageView ib_home_shop;
    private ImageView ib_home_order;
    private ImageView ib_home_task;
    private ImageView ib_home_my;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store_address_correct);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.title), false);
        mCustomer = (Customer) getIntent().getExtras().get("customer");
        tv_aboutus = (TextView) findViewById(R.id.title_text);
        tv_aboutus.setText("修改地址");
        title_reback = (LinearLayout) findViewById(R.id.title_reback);
        title_reback.setOnClickListener(this);
        title_order = (TextView) findViewById(R.id.title_order);
        title_order.setText("提交");
        title_order.setOnClickListener(this);
        tv_current_address = (TextView) findViewById(R.id.tv_current_address);
        tv_current_address.setText(SharedPreference.getPreferString("descAddress"));
        tv_current_address.setOnClickListener(this);
        tv_distance = (TextView) findViewById(R.id.tv_distance);
        if (!StringUtil.isEmpty(mCustomer.getDistance())) {
            tv_distance.setText(mCustomer.getDistance() + "km");
        }
        rl_take_picture = (RelativeLayout) findViewById(R.id.rl_take_picture);
        rl_take_picture.setOnClickListener(this);
        sdv_picture = (SimpleDraweeView) findViewById(R.id.sdv_picture);
        tv_take_picture = (TextView) findViewById(R.id.tv_take_picture);
        initTabView();
    }

    private void initTabView() {
        re_home_shop = (RelativeLayout) findViewById(R.id.re_home_shop);
        re_home_order = (RelativeLayout) findViewById(R.id.re_home_order);
        re_home_task = (RelativeLayout) findViewById(R.id.re_home_task);
        re_home_my = (RelativeLayout) findViewById(R.id.re_home_my);
        re_home_shop.setOnClickListener(this);
        re_home_order.setOnClickListener(this);
        re_home_task.setOnClickListener(this);
        re_home_my.setOnClickListener(this);

        ib_home_shop = ((ImageView) findViewById(R.id.ib_home_shop));
        ib_home_order = ((ImageView) findViewById(R.id.ib_home_order));
        ib_home_task = ((ImageView) findViewById(R.id.ib_home_task));
        ib_home_my = ((ImageView) findViewById(R.id.ib_home_my));

        tv_home_shop = ((TextView) findViewById(R.id.tv_home_shop));
        tv_home_order = ((TextView) findViewById(R.id.tv_home_order));
        tv_home_task = ((TextView) findViewById(R.id.tv_home_task));
        tv_home_my = ((TextView) findViewById(R.id.tv_home_my));

        ib_home_shop.setImageResource(R.drawable.tab_infomation_clk);
        tv_home_shop.setTextColor(getResources().getColor(R.color.title));

        ib_home_order.setImageResource(R.drawable.tab_schedule);
        tv_home_order.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        ib_home_task.setImageResource(R.drawable.tab_service);
        tv_home_task.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        ib_home_my.setImageResource(R.drawable.tab_contacts);
        tv_home_my.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_reback:
                finish();
                break;
            case R.id.re_home_shop:
                showMain(1);
                break;
            case R.id.re_home_order:
                showMain(2);
                break;
            case R.id.re_home_task:
                showMain(3);
                break;
            case R.id.re_home_my:
                showMain(4);
                break;
            case R.id.rl_take_picture:
                takePhoto();
                break;
            case R.id.title_order:
                if (Utils.isNetworkConnected(this)) {
                    if (!StringUtil.isEmpty(SharedPreference.getPreferString("descAddress")) && !StringUtil.isEmpty(mImagePath)) {
                        sendAddress(SharedPreference.getPreferString("descAddress"), new File(mImagePath));
                    } else {
                        ToastUtils.show("请确认地址或图片存在");
                    }
                } else {
                    ToastUtils.show("网络异常，无法提交");
                }
                break;
            case R.id.tv_current_address:
                tv_current_address.setText(SharedPreference.getPreferString("descAddress"));
                break;
        }
    }

    public void takePhoto() {
        if (Environment.getExternalStorageState().equals("mounted")) {
            String fileDir = this.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath();
            SimpleDateFormat localObject2 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
            File imageFile = new File(fileDir, "/" + localObject2.format(new Date()) + ".jpg");
            try {
                photoUri = Uri.fromFile(imageFile);
                if (photoUri == null) {
                    photoUri = FileProvider.getUriForFile(
                            this,
                            "com.ramos.kuaixiao.fileprovider",
                            imageFile);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.d("takePhoto", "takePhoto " + imageFile.getAbsolutePath());
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.putExtra("output", photoUri);
            mImagePath = imageFile.getAbsolutePath();
            Log.d("takePhoto", "mImagePath:" + mImagePath);
            startActivityForResult(intent, 0xa1);
        } else {
            Toast.makeText(this, "内存卡不存在!", Toast.LENGTH_SHORT).show();
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent paramIntent) {
        if (requestCode == 0xa1) {
            Log.d(TAG, "onActivityResult :: requestCode == PHOTO_WITH_CAMERA");
            Glide.with(this).load(mImagePath).dontAnimate().centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(sdv_picture);
            tv_take_picture.setVisibility(View.GONE);
            Bitmap originalbitmap = BitmapFactory.decodeFile(mImagePath);
            showChooseImages(originalbitmap);
        }
        super.onActivityResult(requestCode, resultCode, paramIntent);
    }

    private void showChooseImages(Bitmap originalbitmap) {
        if (originalbitmap != null) {
            savePicture(originalbitmap);
        }
    }

    /**
     * 保存图片到本应用下
     **/
    @SuppressLint("SdCardPath")
    private Bitmap savePicture(Bitmap bitmap) {
        try {
            BufferedOutputStream localBufferedOutputStream = new BufferedOutputStream(
                    new FileOutputStream(new File(mImagePath)));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 10, localBufferedOutputStream);
            localBufferedOutputStream.flush();
            localBufferedOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    private void sendAddress(String address, File image) {
        try {
            if (StringUtil.isEmpty(address)) {
                ToastUtils.show("上传地址不能为空");
                return;
            }
            if (image == null) {
                ToastUtils.show("上传图片不能为空");
                return;
            }
            String url = NetUtils.ADDRESS_CORRECT;
            loading = new CommonLoading(this);
            loading.setLoadText("上传图片中...");
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(10000);
            // 创建请求参数的封装的对象
            RequestParams params = new RequestParams();
            params.put("userId", SharedPreference.getPreferString("id"));
            //params.put("qid", mCustomer.getQid());
            params.put("cid", mCustomer.getId());
            params.put("csId", mCustomer.getHouseId());
            params.put("dealer", mCustomer.getDealer());
            params.put("lon", Double.valueOf(SharedPreference.getPreferString("longitude")));
            params.put("lat", Double.valueOf(SharedPreference.getPreferString("latitude")));
            params.put("address", address);
            params.put("image", image);
            Log.d(TAG, "getTask " + url);
            Log.d(TAG, "getTask " + params.toString());
            // 执行post方法
            client.post(url, params, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    loading.dismiss();
                    Log.d(TAG, "login " + new String(responseBody));
                    com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(new String(responseBody));
                    try {
                        if (jsonObject.getInteger("status") == 200) {
                            sendMessagea(UPLOAD_SUCCESS1, jsonObject.getString("msg"));
                        } else {
                            sendMessagea(UPLOAD_FAIL1, jsonObject.getString("msg"));
                        }
                    } catch (Exception e) {
                        sendMessagea(UPLOAD_FAIL1, "上传异常");
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    loading.dismiss();
                    sendMessagea(UPLOAD_FAIL1, "上传异常");
                    error.printStackTrace();// 把错误信息打印出轨迹来
                }
            });
        } catch (Exception e) {
            loading.dismiss();
            sendMessagea(UPLOAD_FAIL1, "上传异常");
            e.printStackTrace();
        }
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_SUCCESS1:
                    ToastUtils.show("地址纠错申请成功");
                    finish();
                    break;
                case UPLOAD_FAIL1:
                    ToastUtils.show(msg.obj.toString());
                    break;
                default:
                    break;
            }
        }
    };

    private void sendMessagea(int iWhat, Object obj) {
        Message msg = Message.obtain();
        msg.what = iWhat;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }
}


